//
//  LookForCarViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/29.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "LookForCarViewController.h"
#import "CZSearchBar.h"
#import "FindCarTableViewCell.h"
#import "DOPDropDownMenu.h"
#import <MJExtension.h>
#import <MJRefresh.h>
#import "FindCarMode.h"
#import "FindCarResdMode.h"
#import "CarSourceType.h"
#import "Brand.h"
#import "LookForDetailController.h"
#import "SearchTableViewController.h"
#import "SearchMode.h"
#import  "History.h"
#import "PublishQgViewController.h"
@interface LookForCarViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,DOPDropDownMenuDataSource,DOPDropDownMenuDelegate,SearchTableViewDelegate>{
    NSInteger count;
    NSInteger oldcount;
}
@property(nonatomic,strong)CZSearchBar *search;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *brandArray;
@property (nonatomic,strong) NSMutableArray *cartoryArray;
@property (nonatomic,strong) NSMutableArray *locationArray;
@property (nonatomic,strong) NSArray *carsoucearray;
@property (nonatomic,strong) NSArray *brandindexarray;
@property(nonatomic,strong) NSMutableArray *menuarray;
@property (nonatomic,assign) BOOL iscanpost;
@property (nonatomic,strong) NSMutableArray *dataarray;
@property (nonatomic,strong) DOPDropDownMenu *menu;
@property (nonatomic,assign) CGFloat showtime;
@property (nonatomic,assign)  NSInteger brandindex;
@property (nonatomic,copy) NSString *type;
@property (nonatomic,copy) NSString *carad;
@property (nonatomic,copy) NSString *cond;
@end

@implementation LookForCarViewController
+(instancetype)publish{
    LookForCarViewController *plqvc=[[LookForCarViewController alloc]init];
    plqvc.hidesBottomBarWhenPushed=YES;
    return plqvc;
}

-(NSMutableArray *)locationArray{
    if ( _locationArray==nil) {
        _locationArray=[NSMutableArray array];
    }
    return  _locationArray;
}
-(void)searchCilck:(PUSHTYPE)type WithString:(NSString *)string{
    if (type==PUSHTYPEQG) {
        self.cond=string;
        [self.tableView.header beginRefreshing];
    }
}

-(NSMutableArray *)dataarray{
    if ( _dataarray==nil) {
        _dataarray=[NSMutableArray array];
    }
    return  _dataarray;
}

-(NSMutableArray *)menuarray{
    if ( _menuarray==nil) {
        _menuarray=[NSMutableArray array];
    }
    return  _menuarray;
}
-(NSMutableArray *)cartoryArray{
    if ( _cartoryArray==nil) {
        _cartoryArray=[NSMutableArray array];
    }
    return  _cartoryArray;
}
-(NSMutableArray *)brandArray{
    if ( _brandArray==nil) {
        _brandArray=[NSMutableArray array];
    }
    return  _brandArray;
}

-(NSArray *)brandindexarray{
    if ( _brandindexarray==nil) {
        _brandindexarray=[Brand getBrand];
    }
    return  _brandindexarray;
}

-(NSArray *)carsoucearray{
    if (_carsoucearray==nil) {
        _carsoucearray=[CarSourceType getCarSourceType];
    }
    return _carsoucearray;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
    
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.dataarray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FindCarMode *mode=self.dataarray[indexPath.row];
    
    FindCarTableViewCell *cell=[FindCarTableViewCell CellWithTableView:tableView];
    cell.mode=mode;
    cell.selectedbtn.hidden=YES;
    return cell;
}


-(UITableView *)tableView{
    if (_tableView==nil) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 104, XHScreenwidth, XHScreenheight-104) style:UITableViewStylePlain];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.backgroundColor=bgGarycolor;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.search endEditing:YES];
}
- (NSInteger)numberOfColumnsInMenu:(DOPDropDownMenu *)menu {
    return self.menuarray.count;
}
-(void)menu:(DOPDropDownMenu *)menu didSelectRowAtIndexPath:(DOPIndexPath *)indexPath{
    NSLog(@"%ld--%ld",indexPath.row,indexPath.column);
    self.cond=nil;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self preparams:indexPath];
        
    });
}

-(void)preparams:(DOPIndexPath *)indexpath{
   
    switch (indexpath.column) {
        case 0:
            self.brandindex=indexpath.row;
            break;
        case 1:
            self.type=self.cartoryArray[indexpath.row];
            break;
        case 2:
            self.carad=self.locationArray[indexpath.row];
            break;
        default:
            break;
    }
   [self.tableView.header beginRefreshing];
}

-(void)dispatchEqPost{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.menu.show) {
            
        }else{
            NSLog(@"post");
        }
        
    });

}

- (NSInteger)menu:(DOPDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column {
    NSArray *array=self.menuarray[column];
    return array.count;
}
- (NSString *)menu:(DOPDropDownMenu *)menu titleForRowAtIndexPath:(DOPIndexPath *)indexPath {
    NSArray *array=self.menuarray[indexPath.column];
    return array[indexPath.row];
}


-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
-(void)righctlick{
    PublishQgViewController *vc=[PublishQgViewController publish];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    // Do any additional setup after loading the view.
    CZSearchBar *search=[[CZSearchBar alloc]initWithFrame:CGRectMake(0, 0, XHScreenwidth, 30)];
    search.placeholder=@"请输入车镇商品/店铺";
    search.font=[UIFont systemFontOfSize:14];
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.navigationItem.title=@"找求购";
    self.search=search;
    
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"addqg"] style:UIBarButtonItemStyleDone target:self action:@selector(righctlick)];
    
    search.delegate=self;
    self.tableView.contentInset=UIEdgeInsetsMake(0, 0, 56, 0);
    self.tableView.header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadmore)];
    self.navigationItem.title=@"找求购";
    self.tableView.rowHeight=100;
    
    [self setupdata];
    
    DOPDropDownMenu *menu = [[DOPDropDownMenu alloc] initWithOrigin:CGPointMake(0, 64) andHeight:40];
    menu.dataSource = self;
    menu.delegate = self;
    [self.view addSubview:menu];
    self.menu=menu;
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
        
    }
    [self.tableView.header beginRefreshing];

}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    [textField endEditing:YES];
    SearchTableViewController *vc=[[SearchTableViewController alloc]init];
    vc.isFromQG=YES;
    vc.delegate=self;
    [self presentViewController:vc animated:YES completion:nil];
    
}
-(void)loadmore{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    if (self.cond) {
        params[@"action"]=@"s_buy";
        params[@"s_action"]=@"data";
        params[@"num"]=@"6";
        params[@"cond"]=self.cond;
//        if (self.mode.sesion) {
//            params[@"sesion"]=self.mode.sesion;
//        }
    }else{
    params[@"action"]=@"where";
    params[@"num"]=@"6";
    params[@"car_num"]=@"3";
    if (self.brandindex!=0) {
        Brand *brand=self.brandindexarray[self.brandindex-1];
        params[@"brand"]=brand.brand_name;
    }
    if (![self.type isEqualToString:@"车源类型"]&&self.type) {
        params[@"type"]=self.type;
    }
    if (![self.carad isEqualToString:@"交货地点"]&&self.carad) {
        params[@"type"]=self.carad;
    }
    }
    NSString *url;
    
    if (self.cond) {
        url=searchurl;
    }else{
        url=lookforcar;
    }
    

    NSMutableArray *IDarray=[NSMutableArray array];
    for (FindCarMode *mode in self.dataarray) {
        [IDarray addObject:mode.ID];
    }
    
    params[@"page_id"]=[NSString DataTOjsonString:IDarray];
    
    [PostUitls Post:lookforcar parameters:params success:^(id response) {
        
        FindCarResdMode *mode=[FindCarResdMode modeWithDict:response];
       
        if ([mode.state integerValue]==400) {
            if (mode.data.count==6) {
                [self.tableView.footer resetNoMoreData];
            }else{
                [self.tableView.footer noticeNoMoreData];
            }
           
        }else{
             [self.tableView.footer noticeNoMoreData];
        }
        [self.dataarray addObjectsFromArray:mode.data];
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];
        
        
    } failure:^(NSError *error) {
        [self.tableView.footer endRefreshing];
    }];

}

-(void)refresh{
    
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    
    if (self.cond) {
        params[@"action"]=@"s_buy";
        params[@"s_action"]=@"data";
        params[@"num"]=@"6";
        params[@"cond"]=self.cond;
//        if (self.mode.sesion) {
//            params[@"sesion"]=self.mode.sesion;
//        }
    }else{
        params[@"action"]=@"where";
        params[@"num"]=@"6";
        params[@"car_num"]=@"3";
        if (self.brandindex!=0) {
            Brand *brand=self.brandindexarray[self.brandindex-1];
            params[@"brand"]=brand.brand_name;
        }
        if (![self.type isEqualToString:@"车源类型"]&&self.type) {
            params[@"type"]=self.type;
        }
        if (![self.carad isEqualToString:@"交货地点"]&&self.carad) {
            params[@"type"]=self.carad;
        }

    }
    NSString *url;
    
    if (self.cond) {
        url=searchurl;
    }else{
        url=lookforcar;
    }
    
    [PostUitls Post:url parameters:params success:^(id response) {
       
        FindCarResdMode *mode=[FindCarResdMode modeWithDict:response];
          [self.dataarray removeAllObjects];
        if ([mode.state integerValue]==400) {
            if (mode.data.count==6) {
                [self.tableView.footer resetNoMoreData];
            }else{
                [self.tableView.footer noticeNoMoreData];
            }
            [self.dataarray addObjectsFromArray:mode.data];
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];

        
    } failure:^(NSError *error) {
        [self.tableView.header endRefreshing];
    }];
    
    
}



-(void)setupdata{
    [self.brandArray addObject:@"品牌"];
    for (Brand *brand in self.brandindexarray) {
        [self.brandArray addObject:[NSString stringWithFormat:@"%@-%@",brand.brand_desc,brand.brand_name]];
    }
    [self.cartoryArray addObject:@"车源类型"];
    NSArray *array=[CarSourceType getCarSourceType];
    for (CarSourceType *carsource in array) {
        [self.cartoryArray addObject:carsource.name];
    }
    [self.locationArray addObjectsFromArray:@[@"交货地点",@"东区",@"西区",@"南区",@"北区",@"中区"]];
    [self.menuarray addObject:self.brandArray];
    [self.menuarray addObject:self.cartoryArray];
    [self.menuarray addObject:self.locationArray];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   FindCarMode *mode=self.dataarray[indexPath.row];
    LookForDetailController *vc=[LookForDetailController viewcontroller];
    vc.findmode=mode;
    [self.navigationController pushViewController:vc animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
